import cv2
import numpy as np
from matplotlib import pyplot as plt
  
image = cv2.imread('demo.jpg')
hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
cv2.imshow("img", image)

def purple_hsv():
    lower_hsv = np.array([130,247,46])
    higher_hsv = np.array([155,255,255])
    mask= cv2.inRange(hsv_img,lower_hsv,higher_hsv)
    return mask

mask = purple_hsv()
detected_img = cv2.bitwise_and(image,image,mask=mask)

gray = cv2.cvtColor(detected_img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray,93, 255, cv2.THRESH_BINARY+cv2.THRESH_TRIANGLE)
cv2.imshow("img1", thresh)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
    x, y, w, h = cv2.boundingRect(c) 
   
    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    cv2.drawContours(image, [box], 0, (0, 0, 255), 3)
    (x, y), radius = cv2.minEnclosingCircle(c)
    center = (int(x), int(y))
    radius = int(radius)


cv2.drawContours(image, contours, -1, (255, 0, 0), 1)
cv2.imshow("img", image)
cv2.imwrite("img_1.jpg", image)
cv2.waitKey(0)
